package com.topisv.tms.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.UserNotes;
import com.topisv.tms.entity.Task;
import com.topisv.tms.repository.UserNotesDao;
import com.topisv.tms.repository.TaskDao;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class UserNotesService {

	private UserNotesDao userNotesDao;

	public UserNotes getUserNotes(Long id) {
		return userNotesDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void saveUserNotes(UserNotes entity) {
		userNotesDao.save(entity);
	}

	@Transactional(readOnly = false)
	public void deleteUserNotes(Long id) {
		userNotesDao.delete(id);
	}

	public List<UserNotes> getAllUserNotes() {
		return (List<UserNotes>) userNotesDao.findAll();
	}
	
	/**
	 * 分页显示表内所有行.
	 */
	public Page<UserNotes> getUserNotes(Long userNotesId, Map<String, Object> filterParams, int pageNumber, int pageSize,
			String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		return userNotesDao.findAll(pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("user_id".equals(sortType)) {
			sort = new Sort(Direction.ASC, "user_id");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<UserNotes> buildSpecification(Long userNotesId, Map<String, Object> filterParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userNotesId));
		Specification<UserNotes> spec = DynamicSpecifications.bySearchFilter(filters.values(), UserNotes.class);
		return spec;
	}

	@Autowired
	public void setUserNotesDao(UserNotesDao userNotesDao) {
		this.userNotesDao = userNotesDao;
	}
}
